<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
<!--        <el-button type="danger"-->
<!--                   size="small"-->
<!--                   icon="el-icon-delete"-->
<!--                   plain-->
<!--                   v-if="permission.open_address_delete"-->
<!--                   @click="handleDelete">删 除-->
<!--        </el-button>-->
        <el-button type="primary"
                   size="small"
                   plain
                   @click="handleUpdateCode">重新获取距离和编号
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="longitudeAndLatitude">
        <el-tag v-if="row.longitudeAndLatitude !== ''" type="primary">
          {{ longitudeAndLatitudeAddress(row.longitudeAndLatitude) }}
        </el-tag>
        <el-tag v-else type="info">未设置</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isPublic">
        <el-tag v-if="row.isPublic === 1" type="primary">公共</el-tag>
        <el-tag v-else type="warning">私有</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="memberId">
        <el-tag v-if="row.memberName && row.memberName !== ''" type="primary">{{ row.memberName }}</el-tag>
        <el-tag v-else type="info">无</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="distance">
        <el-tag type="primary">{{ row.distance }} km</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isTakeSelf">
        <el-tag v-if="row.isTakeSelf === 1" type="primary">
          自取
        </el-tag>
        <el-tag v-else type="info">配送</el-tag>
      </template>
<!--      <template slot="search" slot-scope="{row,size}">-->
<!--        <div class="el-col el-col-6 el-col-offset-0 el-col-xs-24 el-col-sm-12 el-col-md-6 avue-form__row"-->
<!--             style="padding-left: 10px; padding-right: 10px;"-->
<!--        >-->
<!--          <div class="el-form-item el-form-item&#45;&#45;small avue-form__item&#45;&#45;">-->
<!--            <label class="el-form-item__label" style="width: 80px;">类型：</label>-->
<!--            <el-select v-model="search.isPublic"-->
<!--                       placeholder="公共或私有"-->
<!--                       style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"-->
<!--                       clearable-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in isPublicOptions"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </div>-->
<!--        </div>-->
<!--      </template>-->
    </avue-crud>
    <div id="container"></div>
    <div id="panel"></div>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, updateCode} from "@/api/address/open_address";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      orderDistance: '',
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 3,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: "门店",
            prop: "merchantId",
            row: true,
            span: 24,
            type: "select",
            dicUrl: '/api/merchant/merchant/select',
            search: true,
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "是否自取",
            prop: "isTakeSelf",
            row: true,
            span: 24,
            type: "radio",
            slot: true,
            dicData: [
              {
                label: "是",
                value: 1
              },
              {
                label: "否",
                value: 2
              }
            ],
            value: 2,
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }],
          },
          // {
          //   label: "类型",
          //   prop: "isPublic",
          //   slot: true,
          //   display: false,
          // },
          {
            label: "定位地址",
            prop: "longitudeAndLatitude",
            component: "avueMap",
            type: 'map',
            slot: true,
            overHidden: true,
            row: true,
            span: 24,
          },
          {
            label: "显示地址",
            prop: "addressText",
            slot: true,
            search: true,
            row: true,
            span: 24,
            overHidden: true,
          },
          {
            label: "距离",
            prop: "distance",
            slot: true,
            row: true,
            span: 24,
            overHidden: true,
            display: false,
          },
          // {
          //   label: "地址编号（动态）",
          //   prop: "code",
          //   // sortable: 'custom',
          //   display: false,
          // },
          {
            label: "引用私有地址数量",
            prop: "privateAddressCount",
            display: false,
          },
        ]
      },
      data: [],
      isPublicOptions: [
        {
          value: 1,
          label: '公共'
        }, {
          value: 2,
          label: '私有'
        }
      ],
      search: {
        isPublic: '',
      },
    };
  },
  watch: {
    'form.longitudeAndLatitude'(val) {
      console.log(val)
      let result = val
      if (typeof val === 'string') {
        return
      }
      try {
        if (!result.addressComponent) {
          result.addressComponent = {
            city: result.cityname,
            district: result.adname,
            township: '',
            street: result.name,
            streetNumber: ''
          }
          result.latitude = result.location.lat
          result.longitude = result.location.lng
        }

        this.form.addressText = result.addressComponent.city + result.addressComponent.district + result.addressComponent.township + result.addressComponent.street + result.addressComponent.streetNumber
      } catch (e) {
        // console.log(e)
      }
    },
    'form.isTakeSelf' (val) {
      const longitudeAndLatitudeColumn = this.findObject(this.option.column, "longitudeAndLatitude");
      const addressTextColumn = this.findObject(this.option.column, "addressText");
      if (val === 1) {
        this.$set(longitudeAndLatitudeColumn, 'display', false)
        this.$set(addressTextColumn, 'display', false)
      } else {
        this.$set(longitudeAndLatitudeColumn, 'display', true)
        this.$set(addressTextColumn, 'display', true)
      }
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.open_address_add, false),
        viewBtn: false,
        delBtn: this.vaildData(this.permission.open_address_delete, false),
        editBtn: this.vaildData(this.permission.open_address_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    longitudeAndLatitudeAddress() {
      return (val) => {
        let result = ''
        if (typeof val === 'string') {
          val = JSON.parse(val)
        }
        try {
          result = val.addressComponent.city + val.addressComponent.district + val.addressComponent.township + val.addressComponent.street + val.addressComponent.streetNumber
        } catch (e) {
          console.log(e)
        }
        return result
      }
    },
    longitudeAndLatitudeObj() {
      return (val) => {
        if (typeof val === 'string') {
          val = JSON.parse(val)
        }
        return val
      }
    },
  },
  methods: {
    handleNavTo(row) {
      const longitudeAndLatitude = row.longitudeAndLatitude
      const merchantLongitudeAndLatitude = row.merchantLongitudeAndLatitude

      var map = new AMap.Map("container", {
        resizeEnable: true,
        center: [116.397428, 39.90923],//地图中心点
        zoom: 13 //地图显示的缩放级别
      });
      var riding = new AMap.Riding({
        map: map,
        panel: "panel"
      });
      //根据起终点坐标规划骑行路线
      riding.search([116.397933,39.844818],[116.440655,39.878694], function(status, result) {
        // result即是对应的骑行路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
        if (status === 'complete') {
          console.log('绘制骑行路线完成')
        } else {
          this.$message.warning('骑行路线数据查询失败' + result)
        }
      });
    },
    handleUpdateCode() {
      this.$confirm("此操作将向高德地图获取相应数据，执行后更新较慢，确定重新获取获取距离和地址编号?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return updateCode();
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功, 数据更新较慢, 请稍后查看准确数据!"
          });
        });
    },
    sortChange(column) {
      this.orderDistance = ''

      let order = ''
      switch (column.order) {
        case 'ascending':
          order = 'ASC'
          break;
        case 'descending':
          order = 'DESC'
          break;
        default:
          order = ''
          break
      }

      if (column.prop === 'distance') {
        this.orderDistance = order
      }
      this.onLoad(this.page)
    },
    rowSave(row, done, loading) {
      if (row.longitudeAndLatitude) {
        row.longitudeAndLatitude = JSON.stringify(row.longitudeAndLatitude)
      }
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (row.longitudeAndLatitude) {
        row.longitudeAndLatitude = JSON.stringify(row.longitudeAndLatitude)
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("删除将删除关联用户的私有地址，确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          try {
            this.form.longitudeAndLatitude = JSON.parse(this.form.longitudeAndLatitude)
          } catch (e) {
            console.log(e)
          }
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.search.isPublic = '';
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.isPublic = 1
      if (this.orderDistance && this.orderDistance !== '') {
        params.orderDistance = this.orderDistance
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.success-row{
  background-color: #b4e59e !important;
  color: #000000;
}
</style>
